<?php


namespace app\shop\model;

use app\admin\model\Common;
use app\common\traits\ActionRecordTrait;
use think\facade\Db;
use think\model\concern\SoftDelete;
use app\common\traits\UserInfoTrait;

/**
 * 分类model
 * Class GoodsCategory
 * @package app\shop\model
 * @author Mr.Liu Wuchen
 * @create 2021-05-26 14:24
 */
class GoodsCategory extends Common
{
    use SoftDelete;

    use ActionRecordTrait,UserInfoTrait;
    /**
     * 表名
     * @var string
     */
    protected $name = 'shop_goods_category';

    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = 0;

    /**
     * 分类列表
     * 是否不分页  no_page  0/null 分页 1不分页
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-05-26 10:51
     */
    public function getDataList(array $request): array
    {
        try {
            $request = $this->fmtRequest($request);
            $map     = $request['map'] ?? [];
            $where   = [];
            $search  = isset($map['search']) && $map['search'] ? trim($map['search']) : '';
            if ($search) {
                array_push($where, ['name', 'like', '%'.$search.'%']);
            }
            $dataCount = $this->where($where)->count();
            if($dataCount){
                $field = $request['map']['field'] ?? '';
                if(!$field){
                    $field = ['id', 'name', 'sort', 'create_user_id','create_time', 'update_time'];
                }
                $list  = $this->where($where)->field($field)
                    ->when(!(isset($map['no_page']) && $map['no_page']) ,function($query) use ($request){
                        $query->limit(($request['page'] - 1) * $request['limit'], $request['limit']);
                    })
                    ->order('sort DESC')
                    ->select()->toArray();
                if($list){
                    if(in_array('create_user_id',$field)){
                        $userIds = array_column($list,'create_user_id');
                        if($userIds){
                            $userInfo = Db::name('admin_user')->where('id','in',$userIds)->column('realname','id');
                        }
                    }
                    foreach($list as &$item)
                    {
                        if(isset($item['create_user_id'])){
                            $item['create_user_name'] = $userInfo[$item['create_user_id']] ?? '';
                            unset($item['create_user_id']);
                        }
                    }

                }

            }
            $data['list']      = $list;
            $data['dataCount'] = $dataCount ?? 0;
            return $data;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
    }

    /**
     * 新增分类
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-05-26 11:25
     */
    public function addData(array $request): bool
    {
        try {
            // 验证
            $validate = new \app\shop\validate\GoodsCategory();
            if (!$validate->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
            $data = [
                'name'           => trim($request['name']),
                'sort'           => $request['sort'] ?? 0,
                'create_user_id' => session('user_id'),
                'create_time'    => time(),
                'update_time'    => time(),
            ];

            $insertId = $this->insertGetId($data);
            if ($insertId) {
                $this->addActionRecord($request['user']['id'],'shop_goods_category_create',$insertId,'添加商品分类 '.$data['name'],'shop','goods_category');
                $this->error = '添加成功';
                return true;
            }
        } catch (\Exception $e) {
        }
        $this->error = '添加失败';
		return false;
    }

    /**
     * 更新分类
     * @param array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-05-26 11:33
     */
    public function saveData(array $request): bool
    {
        try {
            $id = $request['id'] ?? 0;
            if (!$id) {
                $this->error = '参数错误';
                return false;
            }
            // 验证
            $validate = new \app\shop\validate\GoodsCategory();
            if (!$validate->check($request)) {
                $this->error = $validate->getError();
                return false;
            }
            $data = [
                'name'        => trim($request['name']),
                'sort'        => $request['sort'] ?? 0,
                'update_time' => time(),
            ];
            $goodsCategory = $this->field('id,name')->find($id);
            $goodsCategory ? $goodsCategory = $goodsCategory->toArray() : '';
            if($goodsCategory){
                $bool = $this->where(['id'=>$id])->update($data);
                $content = '';
                if($goodsCategory['name'] != $data['name']){
                    $content .= '编辑了产品分类，分类名称：【'.$goodsCategory['name'].'】 -> ' . ' 【'.$data['name'].'】 ';
                }
                if($content){
                    $this->addActionRecord($request['user']['id'],'shop_goods_category_update',$id,$content,'shop','goods_category');
                }
                if ($bool) {
                    $this->error = '更新成功';
                    return true;
                }
            }
        } catch (\Exception $e) {

        }
        $this->error = '更新失败';
		return false;
    }

    /**
     * 删除分类
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-05-26 15:09
     */
    public function deleteData(array $request): bool
    {
        try {
            $requestId = isset($request['id']) && $request['id'] ? $request['id'] : [];
            if (!$requestId) {
                $this->error = '参数错误';
                return false;
            }

            $idArr = is_array($requestId) ? $requestId : explode(',', $requestId);
            $where = [
                ['id', 'in', $idArr]
            ];


            // 判断分类下存在商品
            if(Db::name('shop_goods')->where('category_id','in',$idArr)->where('delete_time','=',0)->value('id')){
                $this->error = '该分类下存在商品，请先删除商品';
                return false;
            }
            $bool = self::destroy(function($query) use ($where){
                $query->where($where);
            });

            if ($bool) {
                $this->error = '删除成功';
                foreach($idArr as $id){
                    $this->addActionRecord($request['user']['id'],'shop_goods_category_delete',$id,'删除商品分类','shop','goods_category');
                }
                return true;
            }
        } catch (\Exception $e) {

        }
        $this->error = '删除失败';
		return false;
    }

    /**
     * 商品分类详情
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-06-09 14:29
     */
    public function getDataDetail(array $request): array
    {
        $goodsCategoryDetail = [];
        try {
            $id = $request['id'] ?? 0;
            if(!$id){
                $this->error = '请输入商品分类id';
                return false;
            }
            $detail = self::find($id);
            if($detail){
                $goodsCategoryDetail = $detail->toArray();
                $goodsCategoryDetail['create_user_name'] = $this->getUserValue($goodsCategoryDetail['create_user_id'],'realname');
            }

        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            return [];
        }
        return $goodsCategoryDetail;
    }

}
